
package com.gcloud.mesh.monitor.timer;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Timers {

    static Logger LOG = LoggerFactory.getLogger(Timers.class);

    private static final Map<String, ITimer> timers = new HashMap<>();

    /**
     * 注册定时线程
     * @param timer 所有继承BaseTimer的子类
     */
    public static void register(ITimer timer) {
        register(timer.getClass().getSimpleName(), timer);
    }

    public static void register(String name, ITimer timer) {
        register(name, timer, timer.autoStart());
    }

    public static void register(String name, ITimer timer, boolean startIt) {
        if (timers.get(name) != null) {
            LOG.error(String.format("register error, timer already exists:%s", name));
        }
        else {
            LOG.info(String.format("register timer:%s -> %s", name, timer.getClass().getSimpleName()));
            timers.put(name, timer);
            if (startIt) {
                LOG.info(String.format("starting timer:%s -> %s", name, timer.getClass().getSimpleName()));
                if (timer.init()) {
                    timer.start();
                }
            }
        }
    }

    /**
     * 停止所有已注册定时线程
     */
    public static void stop() {
        for (Map.Entry<String, ITimer> timer : timers.entrySet()) {
            LOG.info(String.format("stopping timer:%s", timer.getKey()));
            timer.getValue().stop();
        }
    }

    public static void remove(String name) {
        ITimer timer = timers.get(name);
        if (timer != null) {
            LOG.info(String.format("stopping timer:%s", name));
            timer.stop();
            timers.remove(name);
        }
    }

}
